<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/29
 * Time: 17:09
 */

namespace app\api\model;


use app\api\exception\BaseException;

class Sendcode extends BaseModel
{
    //写入验证码
    public static function add($mobile)
    {
        $code = get_rand_char(6);
        $info = self::get($mobile);
        if ($info) {
            $info->code = $code;
            $info->mobile = $mobile;
            $info->add_time = time();
            $info->expiretime = time() + config('config.验证码_时效') * 60;
            $res = $info->save();
        } else {
            $data = [
                'code' => $code,
                'mobile' => $mobile,
                'add_time' => time(),
                'expiretime' => time() + config('config.验证码_时效') * 60
            ];
            $res = self::create($data);
        }
        return $res;
    }

    //验证验证码
    public static function check($mobile, $code)
    {
        return  ;
        $info = self::get(['mobile' => $mobile]);
        if (!$info) {
            throw new BaseException(['msg' => '发送记录不存在', 'errorCode' => 1]);
        }
        if ($info['status'] == 1) {
            throw new BaseException(['msg' => '验证码已验证', 'errorCode' => 1]);
        }
        if ($info['expiretime'] < time()) {
            throw new BaseException(['msg' => '验证码已过期', 'errorCode' => 1]);
        }
        if ($info['code'] != $code ) {
            throw new BaseException(['msg' => '验证码错误', 'errorCode' => 1]);
        }
        $info->status = 1;
        $info->save();
        return true;
    }


    /**
     * 发送短信
     * @return boolean
     * @return stdClass
     */
    public static function sendSms($mobile, $type)
    {
        import('aliyun-dysms.api_demo.SmsDemo', EXTEND_PATH, '.php');
        $code = generate_code(6);
        $info = self::get(['mobile' => $mobile]);
        if($info['expiretime'] > time() && $info['status'] == 0){
            throw new BaseException(['msg'=>'','errorCode'=>0,'data'=>['status'=>1,'msg'=>'短信验证码30分钟内有效,请勿重复发送']]);
        }
        if ($info) {
            $info->code = $code;
            $info->mobile = $mobile;
            $info->type = $type;
            $info->isexpire = 0;
            $info->status = 0;
            $info->add_time = time();
            $info->expiretime = time() + config('config.验证码_时效');
            $res = $info->save();
        } else {
            $data = [
                'mobile' => $mobile,
                'code' => $code,
                'type' => $type,
                'isexpire' => 0,
                'status' => 0,
                'add_time' => time(),
                'expiretime' => time() + config('config.验证码_时效') //短信过期时间5分钟
            ];
            $res = self::create($data);
        }
        if (!$res) {
            return false;//短信发送失败
        }

        $response = \SmsDemo::sendSms($mobile, $code);
        return $response;
    }


}